﻿
Imports VSModel
Imports System.Data
Imports Cls_Common
Imports TemplateParser
Partial Class FrontEnd_Control_ShoppingCart
    Inherits System.Web.UI.UserControl
    Dim _CartId As String
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'hien thi thong tin
        _CartId = Session("CartId")
        If Not Page.IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If

            ShowShoppingCartList()
            CalculateSumPrice()
            btnCheckOut.Attributes.Add("onClick", "javascript: return ThanhToan();")
            '    AddShoppingCart(3, 4, 1)
        End If
    End Sub
    Private Sub AddShoppingCart(ByVal _ProductID As String, ByVal _StoreId As Integer, ByVal quantity As Integer)
        'Dim cls As New clsDACart
        'Dim dt As New DataTable
        'cls.CartID = _CartId
        'cls.ProductID = Request("ProductID")
        'cls.Quantity = quantity
        'cls.Insert_ShoppingCart()
        'cls.Destructor()
        'cls = Nothing
        Using Data As New VSEntities
            Dim p As New VSModel.ShoppingCart
            p.CartId = _CartId
            p.ProductId = _ProductID
            If Not Session("UserId") Is Nothing Then
                p.UserId = Session("UserId")
            End If

            p.Quantity = quantity
            Data.ShoppingCarts.AddObject(p)
            Data.SaveChanges()
        End Using


    End Sub

    Private Sub ShowShoppingCartList()
        Using Data As New VSEntities
            Dim p = (From q In Data.ShoppingCarts Where q.CartId = _CartId Select q).ToList

            With ShpCartList
                .DataKeyField = "ProductID"
                .DataSource = p
                .DataBind()
            End With

            hidProductCount.Value = p.Count

            'get information from users
            If Not Session("UserId") Is Nothing Then
                Dim _UserId As Integer = Session("UserId")
                Dim u = (From q In Data.Users Where q.UserId = _UserId Select q.FullName, q.DiaChi, q.Phone, q.Email).FirstOrDefault
                If Not u Is Nothing Then
                    txtCustomerName.Text = u.FullName
                    txtCustomerAddress.Text = u.DiaChi
                    txtCustomerPhone.Text = u.Phone
                    txtCustomerEmail.Text = u.Email
                End If
            End If
        End Using
    End Sub

    Protected Function ImgPath(ByVal ImgSmall As String) As String
        If ImgSmall <> "" Then
            Return ImgSmall
        Else
            Return MainDomain & "NoImages.jpg"
        End If

    End Function

    Private Sub UpdateShoppingCart()
        ' Iterate through all rows within shopping cart list
        Dim i As Integer
        For i = 0 To ShpCartList.Items.Count - 1
            Dim remove As CheckBox = CType(ShpCartList.Items(i).FindControl("Remove"), CheckBox)
            Dim lblProductCode As Label = CType(ShpCartList.Items(i).FindControl("lblProductCode"), Label)
            ' If the quantity field is changed or delete is checked
            If remove.Checked = True Then
                If remove.Checked = True Then
                    RemoveItem(lblProductCode.Text)
                End If
            End If
            ' update quantity
            Dim Qty As String = CType(ShpCartList.Items(i).FindControl("txtQuantity"), TextBox).Text
            If IsNumeric(Qty) Then
                If Qty <= 0 Then Qty = 1
                If Qty > 999 Then Qty = 999
                UpdateCart(lblProductCode.Text, Qty)
                CalculateSumPrice()
            End If
        Next
    End Sub
    ' remove an item from shopping cart
    Private Sub RemoveItem(ByVal _ProductCode As String)

        Using Data As New VSEntities
            Dim p As New VSModel.ShoppingCart
            p = (From q In Data.ShoppingCarts Where q.CartId = _CartId And q.Product.Code = _ProductCode Select q).FirstOrDefault
            Data.ShoppingCarts.DeleteObject(p)
            Data.SaveChanges()
        End Using

    End Sub
    'Update cart
    Private Sub UpdateCart(ByVal _ProductCode As String, ByVal Quantity As Integer)

        Using Data As New VSEntities
            Dim p As New VSModel.ShoppingCart

            p = (From q In Data.ShoppingCarts Where q.CartId = _CartId And q.Product.Code = _ProductCode Select q).FirstOrDefault
            If Not p Is Nothing Then
                p.Quantity = Quantity
                Data.SaveChanges()
            End If

        End Using


    End Sub
    'tinh tong tien theo cartID
    Private Sub CalculateSumPrice()


        Using Data As New VSEntities
            Dim p As VSModel.CalculateSumPriceByCartID_Result = Data.CalculateSumPriceByCartID(_CartId).FirstOrDefault
            If Not p Is Nothing AndAlso Not p.sumPrice Is Nothing Then
                lblTongTien.Text = FormatCurrency(p.sumPrice, ",", ".")
            Else
                lblTongTien.Text = ""
            End If

        End Using
    End Sub

    Protected Sub ShpCartList_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles ShpCartList.ItemDataBound

        Dim row = CType(e.Item.DataItem, VSModel.ShoppingCart)

        Dim hplTitle As HyperLink = CType(e.Item.FindControl("hplTitle"), HyperLink)


        Dim hplStore As HyperLink = CType(e.Item.FindControl("hplStore"), HyperLink)

        Dim lblPrice As Label = CType(e.Item.FindControl("lblPrice"), Label)
        Dim lblProductCode As Label = CType(e.Item.FindControl("lblProductCode"), Label)

        Dim lblSumPrice As Label = CType(e.Item.FindControl("lblSumPrice"), Label)
        If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
            ' If script return true: cAll Postback 

            Dim Qty As String = CType(e.Item.FindControl("txtQuantity"), TextBox).Text
            lblPrice.Text = FormatCurrency(row.Product.SellPrice, ",", ".")
            lblSumPrice.Text = FormatCurrency(row.Product.SellPrice * CInt(Qty), ",", ".")
            hplTitle.Text = row.Product.Title

            hplTitle.NavigateUrl = MainDomain & row.Product.QueryString & "-" & row.Product.ProductId & ".html"
            lblProductCode.Text = row.Product.Code
            ''store
            'hplStore.Text = row.Store.Title
            'hplStore.NavigateUrl = MainDomain & row.Store.QueryString & "-" & row.Product.Store.StoreId & "/store.html"

        End If
    End Sub

    Protected Sub btnUpdate_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        UpdateShoppingCart()
        ShowShoppingCartList()
        CalculateSumPrice()
        Excute_Javascript("updateCart();", Me.Page)
    End Sub


    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Using Data As New VSEntities
            'update lại userid trong Cart
            Dim check = (From q In Data.ShoppingCarts Where q.CartId = _CartId Select q).FirstOrDefault
            If Not check Is Nothing Then
                check.UserId = Session("UserId")
                ' p.StoreId = (From q In Data.Products Where q.ProductId = _ProductID Select q.StoreId).FirstOrDefault
                Data.SaveChanges()
            End If

            Dim p As New VSModel.Order
            p.CartId = _CartId
            p.CustomerName = txtCustomerName.Text.Trim()
            p.Address = txtCustomerAddress.Text.Trim()
            p.Email = txtCustomerEmail.Text.Trim()
            p.Phone = txtCustomerPhone.Text.Trim()
            p.OrderDate = Now()

            p.Note = txtCustomerNote.Text.Trim()
            p.StatusId = 1
            If Not Session("UserName") Is Nothing Then
                p.Creator = Session("UserName")
            End If


            Data.Orders.AddObject(p)
            Data.SaveChanges()

            'send email thong bao
            Dim templatevars As New Hashtable()
            templatevars.Add("FullName", txtCustomerName.Text)
            templatevars.Add("DiaChi", txtCustomerAddress.Text)
            templatevars.Add("Email", txtCustomerEmail.Text)
            templatevars.Add("Phone", txtCustomerPhone.Text)
            templatevars.Add("Note", txtCustomerNote.Text)

            templatevars.Add("ReceiptNo", Session("CartId"))
            templatevars.Add("DateOrder", Now.ToString("dd/MM/yyyy"))

            templatevars.Add("TongTien", lblTongTien.Text)


            'for detail orders
            Dim detail = (From q In Data.ShoppingCarts Where q.CartId = _CartId Select q).ToList
            Dim str As String = ""
            Dim i As Integer = 1
            For Each a In detail
                str = str + "<tr><td>" & i.ToString & "</td>" & _
                        "<td>" & a.Product.Code & "</td>" & _
                         "<td>" & a.Product.Title & "</td> " & _
                         "<td>" & a.Product.SellPrice & "</td> " & _
                         "<td>" & a.Quantity & "</td> " & _
                         "<td>" & FormatCurrency(a.Product.SellPrice * a.Quantity, ",", ".") & "</td> " & _
                        "</tr> "

                i = i + 1
            Next
            templatevars.Add("ThongTinDonHang", str)




            Dim parser As New Parser(Server.MapPath("~/frontend/emailtemplate/Invoice.htm"), templatevars)

            Sendmail_SMTP("no-reply@matbushop.vn", "no-reply", "matbushop.vn", txtCustomerEmail.Text, "", "Matbushop - don hang", parser.Parse, "Matbushop@123", 25, False)
            Sendmail_SMTP("no-reply@matbushop.vn", "no-reply", "matbushop.vn", "nghiavt@gmail.com", "", "Matbushop - don hang", parser.Parse, "Matbushop@123", 25, False)



            'add cart mới
            Session("CartId") = Guid.NewGuid().ToString

        End Using
        Response.Redirect(MainDomain & "Page/Thanks.aspx")

    End Sub
End Class
